import { reactive } from 'vue'
import type { httpReturnPage } from '@/api/api'

const createPageParam = () => ({
  pageNum: 1,
  pageSize: 10
})

const createStatus = () => ({
  loading: false, // 是否正在加载
  finished: false, // 是否全部加载完成 => 条数等于list的长度
  error: false, // 是否加载出错 => 可以点击底部状态重新触发加载
  refreshing: false // 下拉刷新状态
})

export default function useList<FormType, ListType>(
  form: FormType,
  onLoad: (params: ReturnType<typeof createPageParam> & FormType) => httpReturnPage<ListType>
) {
  // 存储列表
  const list: ListType[] = reactive([])
  // 列表状态
  const status = reactive(createStatus())
  // 分页参数
  const pageParam = reactive(createPageParam())

  // 查询列表
  const loadList = async () => {
    status.loading = true
    try {
      const { rows, total } = await onLoad({
        ...pageParam,
        ...form
      })
      list.push(...rows)
      if (list.length === total) {
        status.finished = true
        return
      } else {
        status.finished = false
      }
      pageParam.pageNum++
    } catch (err) {
      status.error = true
      console.error('loadList => err', err)
    } finally {
      status.loading = false
      status.refreshing = false
    }
  }

  const resetParams = () => {
    // 清空列表数组
    list.length = 0
    // 重置分页参数
    Object.assign(pageParam, createPageParam())
  }

  // 重置分页后查询
  const reloadList = () => {
    resetParams()
    // 查询列表
    loadList()
  }

  return {
    loadList,
    reloadList,
    resetParams,
    list,
    status
  }
}
